package edu.uoc.tfc.web;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;

import edu.uoc.tfc.web.criteria.SearchCriteria;


public class EmktAction extends org.apache.struts.action.Action {
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void parseCriteria(HttpServletRequest request, ActionForm form) {
		
		@SuppressWarnings("rawtypes")
		final java.util.Map parameters = new java.util.HashMap();
        for (final java.util.Enumeration names = request.getParameterNames(); names.hasMoreElements();)
        {
            final String name = String.valueOf(names.nextElement());
            parameters.put(name, request.getParameter(name));
        }
        
        String firstResult = (String) parameters.get("firstResult");
        if (firstResult == null) {
        	firstResult = (String) parameters.get("iDisplayStart");
        }
        
        if (firstResult != null) {
        	Class classForm = form.getClass();
        	Field[] fields = classForm.getDeclaredFields();
        	
        	try{
	        	for (Field field : fields) {
	        		if(SearchCriteria.class.isAssignableFrom(field.getType())){
	        			String fieldName = field.getName();
	        			this.setFirstResult(form, fieldName, firstResult);
	        		}
				}
        	} catch (Exception ex) {
        		//TODO:HACER ALGO
        	}
        }

	}



	protected void checkReadonly(HttpServletRequest request)
	{
		if (
			request.getParameter("readonly") == null &&
			request.getAttribute("readonly") == null
		){
			request.setAttribute("readonly", "false");
		}
		else
		if (request.getParameter("readonly") != null)
		{
			request.setAttribute("readonly", request.getParameter("readonly"));
		}
	}



	private void setFirstResult(
			ActionForm form, 
			String fieldName,
			String firstResult) 
					throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		
		Class classForm = form.getClass();
		Object obj = null;
		
		Method[] getterMethods = classForm.getMethods();
		for (Method method : getterMethods) {
			if(method.getName().equalsIgnoreCase("get" + fieldName)){
				obj = method.invoke(form, new Object[]{});
				break;
			}
		}
		
		if (obj != null) {
			SearchCriteria searchCriteria = (SearchCriteria) obj;
			searchCriteria.setFirstResult(Integer.parseInt(firstResult));
		}
	}
}
